<?php
// 数据库配置
define('DB_HOST', 'localhost');
define('DB_NAME', '');		//数据库名
define('DB_USER', '');		//用户名
define('DB_PASS', '');		//密码
define('DB_CHARSET', 'utf8mb4');

// 创建数据库连接
function getDBConnection() {
    try {
        $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET;
        $pdo = new PDO($dsn, DB_USER, DB_PASS);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
        return $pdo;
    } catch (PDOException $e) {
        die("数据库连接失败: " . $e->getMessage());
    }
}

// 获取计时器数据
function getTimerData() {
    $pdo = getDBConnection();
    $stmt = $pdo->prepare("SELECT * FROM timer_data WHERE id = 1");
    $stmt->execute();
    $data = $stmt->fetch();
    
    // 确保数据类型正确
    if ($data) {
        $data['is_running'] = (bool)$data['is_running'];
        $data['elapsed_time'] = (int)$data['elapsed_time'];
        $data['blue_score'] = (int)$data['blue_score'];
        $data['red_score'] = (int)$data['red_score'];
        $data['start_time'] = $data['start_time'] !== null ? (int)$data['start_time'] : null;
    }
    
    return $data;
}

// 更新计时器数据
function updateTimerData($data) {
    $pdo = getDBConnection();
    
    $fields = [];
    $params = [':id' => 1];
    
    if (array_key_exists('start_time', $data)) {
        $fields[] = 'start_time = :start_time';
        $params[':start_time'] = $data['start_time'] !== null ? (int)$data['start_time'] : null;
    }
    
    if (array_key_exists('is_running', $data)) {
        $fields[] = 'is_running = :is_running';
        $params[':is_running'] = $data['is_running'] ? 1 : 0;
    }
    
    if (array_key_exists('elapsed_time', $data)) {
        $fields[] = 'elapsed_time = :elapsed_time';
        $params[':elapsed_time'] = (int)$data['elapsed_time'];
    }
    
    if (array_key_exists('blue_score', $data)) {
        $fields[] = 'blue_score = :blue_score';
        $params[':blue_score'] = (int)$data['blue_score'];
    }
    
    if (array_key_exists('red_score', $data)) {
        $fields[] = 'red_score = :red_score';
        $params[':red_score'] = (int)$data['red_score'];
    }
    
    if (!empty($fields)) {
        $sql = "UPDATE timer_data SET " . implode(', ', $fields) . ", last_updated = NOW() WHERE id = :id";
        $stmt = $pdo->prepare($sql);
        return $stmt->execute($params);
    }
    
    return false;
}

// 初始化数据库（如果表不存在）
function initDatabase() {
    $pdo = getDBConnection();
    
    // 检查表是否存在
    $stmt = $pdo->query("SHOW TABLES LIKE 'timer_data'");
    if ($stmt->rowCount() === 0) {
        // 创建表
        $pdo->exec("
            CREATE TABLE timer_data (
                id INT PRIMARY KEY AUTO_INCREMENT,
                start_time BIGINT DEFAULT NULL,
                is_running TINYINT(1) NOT NULL DEFAULT 0,
                elapsed_time INT NOT NULL DEFAULT 0,
                blue_score INT NOT NULL DEFAULT 0,
                red_score INT NOT NULL DEFAULT 0,
                last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
        ");
        
        // 插入初始数据
        $pdo->exec("INSERT INTO timer_data (id) VALUES (1)");
    }
}

// 自动初始化数据库
initDatabase();
?>